<template>
		<!-- <view style="display: flex;flex-direction: column;"> -->
		<z-paging ref="paging" v-model="messages" use-virtual-list loading-more-no-more-text="我也是有底线的！" @query="queryList">
			<template v-slot:cell="{item,index}">
				<view  style="display: flex;padding: 5px;max-width: 320px;margin-bottom: 20px;"
					:style="{
						alignSelf: index%2 == 0?'flex-start':'flex-end',
						flexDirection:index%2 == 0?  'row' : 'row-reverse'
					}"
				>
				
	<!-- 			<view  v-for="(item,index) in messages" :key="index" style="display: flex;padding: 5px;max-width: 320px;margin-bottom: 20px;"
					:style="{
						alignSelf: index%2 == 0?'flex-start':'flex-end',
						flexDirection:index%2 == 0?  'row' : 'row-reverse'
					}"
				> -->
					<!-- 头像 -->
					<view style="padding:5px">
						<u-avatar  :src="absUrl('/static/avatars/1.jpg')"></u-avatar>
					</view>
					
					<!-- 消息 -->
					<view style="display: flex;flex-direction: column;"
						:style="{
							alignItems: index%2 == 0?'flex-start':'flex-end'
						}"
					>
						<!-- 时间 -->
						<view style="padding: 5px 0;font-size: 22rpx;color:#999">2023-08-26 18:48:53</view>
						  
						<!-- 消息框 -->
						<view style="box-shadow: 0 0px 8px 0px #66666622;">
							<!-- 文字消息 -->
							<view v-if="item.type == 'text'" style="padding: 8px;border-radius: 8px;background-color: white;">
								<text :selectable="true">{{item.text}}</text>
							</view>
							
							<!-- 图片消息 -->
							<view v-if="item.type == 'img'" style="padding: 0px;border-radius: 5px;background-color: white;">
								<u--image  :src="item.message_size?absUrl(item.src):''" 
									:width="messageSize(item).width" 
									:height="messageSize(item).height" 
									@click="onPreview(absUrl(item.src))">
								</u--image>
							</view>
							
							<!-- 视频消息 -->
							<view v-if="item.type == 'video'" @click="previewVideo(item)" style="padding: 0px;border-radius: 5px;background-color: white;position: relative;">
								<u--image  :src="videoThumb(item)" 
									:width="messageSize(item).width" 
									:height="messageSize(item).height" 
									>
								</u--image>
								
								<view v-if="videoThumb(item) != ''" style="position: absolute;left: 50%;top:50%;transform: translate(-50%,-50%);">
									<u-icon name="play-circle" color="white" size="45"></u-icon>
								</view>
							</view>
						</view>
					</view>
				</view>
			</template>
		</z-paging>

		<u-overlay :show="showPreviewVideo" @click="clickOverlay" :customStyle="{zIndex:1}">
			<view v-if="showPreviewVideo" style="position: absolute;left: 50%;top:50%;transform: translate(-50%,-50%);" @longpress="longPressVideo" @click.native.stop="">
				<video
					:src="absUrl(videoPreviewMessage.src)" 
					controls
					autoplay
					http-cache
					:poster="videoPreviewMessage.thumb"
					:style="{
						width :previewSize(videoPreviewMessage).width + 'px',
						height:previewSize(videoPreviewMessage).height + 'px'
					}"
				></video>
			</view>
		</u-overlay>
		
		<!-- <video id="video"></video> -->
		
		<!-- 衬底 -->
		<view style="height: 60px;"
			:style="{
				height:showTools? '360px':'60px'
			}"
		></view>
		
		<!-- 输入栏 -->
		<view style="position: fixed;bottom: 0;left: 0;width: 100%" @touchmove.stop.prevent="disabledScroll">
			<view style="height: 60px;background-color: #f8f8f8;display: flex;justify-content: space-between;align-items: center;border-top: solid 1rpx #eee;">
				<!-- 左按钮 -->
				<view @click="onClickToolsButton" style="padding:10px;margin: 0 10px;background-color: #fff;border-radius: 100px;box-shadow: 0 0 3px 0px #66666622;border: solid 1rpx #eee;">
					<u-icon name="list"></u-icon>
				</view>
				
				<view style="
					flex:1;
					height:35px;
					margin:10px 0;
					background-color: blue;
					border-radius: 5px;
					display: flex;
					justify-content: flex-start;
					align-items: center;
					background-image: linear-gradient(45deg,#ffffff,#ffffff);
					text-align: left; 
					
				">
					<view style="padding: 0 0px;width: 100%;">
						<u--input v-model="textInput" placeholder="输入文本消息" @click="onInputFocus"></u--input>
					</view>
				</view>
				
				<view @click="sendText" style="
					width: 80px;
					height:35px;
					margin:10px;
					background-color: blue;
					border-radius: 80px;
					display: flex;
					justify-content: center;
					align-items: center;
					background-color: white;
					box-shadow: 0 0 3px 0px #66666622;
				">
					发送
				</view>
			</view>
			
			<view v-if="showTools" style="height: 300px;width: 100%;background-color: #eee;"></view>
		</view>
</template>
 
<script>
import ZPMixin from '@/uni_modules/z-paging/components/z-paging/js/z-paging-mixin'
	export default {
		//注意这一步不要漏掉，必须注册mixins(如果全局引入了，就不要这一步，全局引入示例见main.js)
		mixins: [ZPMixin],
		async onShow(){

		},
		computed:{
			messageSize() {
				return (message)=>{
					return message.message_size ? message.message_size : {width:100,height:100}
				}
			},
			previewSize() {
				return (message)=>{
					return message.preview_size ? message.preview_size : {width:300,height:200}
				}
			},
			videoThumb() {
				return (message)=>{
					return message.thumb ? message.thumb : ''
				}
			}
		},
		data() {
			return {
				showTools:false,
				showPreviewVideo:false,
				textInput:'',
				videoPreviewMessage:null,
				messages:[],
				messages_raw:[
					{
						type:'img',
						src:'/static/avatar.jpg',
					},
					{
						type:'img',
						src:'/static/h.jpg'
					},
					{
						type:'img',
						src:'/static/error.png'
					},
					{
						type:'img',
						src:'/static/mm.png'
					},
					{
						type:'video',
						src:'/static/vv.mp4'
					},
					{
						type:'video',
						src:'/static/kk.mp4'
					},
					{
						type:'img',
						src:'/static/logo.png'
					}
				]
			}
		},
		methods: {
			async loadMessage(){
				let promises = []
				
				let messages_raw = JSON.parse(JSON.stringify(this.messages_raw))
				
				messages_raw.forEach((message)=>{
					promises.push(this.regularMessageSize(message))
				})
				
				await Promise.all(promises)
				
				// this.scrollToBottom()
				
				// this.$refs.paging.complete(this.messages_raw);
				
				this.$refs.paging.completeByTotal(messages_raw,2000); 
			},
			queryList(pageNo, pageSize){
				this.loadMessage()
			},
			onClickToolsButton(){
				this.showTools = !this.showTools
				this.scrollToBottom(100,0)
			},
			longPressVideo(){
				// uni.showToast({
				// 	title:'00000'
				// })
				
				// uni.showKeyboard({  showType: 0,  placeholder: '请输入内容',  success: function () {    console.log('键盘弹出成功');  }});
				
				uni.showActionSheet({
					itemList:[
						'下载视频',
						'转发视频'
					]
				})
			},
			scrollToBottom(duration=100,timeout=100)
			{
				setTimeout(()=>{
					uni.pageScrollTo({
						scrollTop:2000000,
						duration
					})
				},timeout)
			},
			async previewVideo(message){
				await this.regularPreviewSize(message)
				this.showPreviewVideo = true
				this.videoPreviewMessage = message
			},
			clickOverlay(){
				this.showPreviewVideo = false
				
				let that = this
				this.$nextTick(()=>{
					that.videoPreviewMessage = null
				})
			},
			async ensureSizeInfo(message)
			{
				if(message.size) return
				
				let imgInfo = null
				
				switch(message.type)
				{
					case 'img':
						imgInfo = await uni.getImageInfo({
							src: this.absUrl(message.src)
						})
						break;
					case 'video':
						console.log(this.absUrl(message.src))
						imgInfo = await uni.getVideoInfo({
							src: this.absUrl(message.src)
						})
						console.log(imgInfo)
						
						message.thumb = await this.getVideoPoster(message,imgInfo.width,imgInfo.height)
						break;
				}
				
				message.size = {width:imgInfo.width,height:imgInfo.height}
			},
			async regularSize(message,maxWidth=200,maxHeight=150)
			{
					try{
						await this.ensureSizeInfo(message)
					}catch(e){
						//TODO handle the exception
						message.size = {width:200,height:200}
					}
					
					//console.log(message.size)
					
					// let length = Math.max(message.size.width,message.size.height)
					// let scale = Math.min(maxWidth / length,1.0)
					
					let widthScale = Math.min(maxWidth / message.size.width,1.0)
					let heightScale = Math.min(maxHeight / message.size.height,1.0)
					let scale = Math.min(widthScale,heightScale,1.0)
					
					// let length = Math.max(message.size.width,message.size.height)
					// let scale = Math.min(maxLength / length,1.0)
					
					let width = Math.floor(message.size.width * scale)
					let height = Math.floor(message.size.height * scale)
					
					width = Math.max(width,30)
					height = Math.max(height,30)
					 
					//console.log(message.size)
					//console.log(width)
					//console.log(height)

					return {width,height}
			},			
			async regularPreviewSize(message){
				//console.log(this.$device.screenWidth())
				message.preview_size = await this.regularSize(message,this.$device.screenWidth(),this.$device.measure.windowHeight * 0.8)
			},		
			async regularMessageSize(message){
				message.message_size = await this.regularSize(message,200)
			},
			onPreview(absUrl){
				uni.previewImage({
					urls:[absUrl]
				})
			},
			sendText(e){
				console.log(e)
				console.log(this.textInput)
				this.messages.push({
					type:'text',
					text:this.textInput
				})
				
				this.textInput = ''
				
				this.scrollToBottom(100,100)
			},
			onInputFocus(){
				
				this.scrollToBottom(0,100)
				this.showTools = false
				//this.scrollToBottom(100,200)
			},
			async getVideoPoster(message,width=200,height=200) {
			  //const that = this;
			  let dataURL = null
			  //let video = uni.createVideoContext('video-for-draw')
			  let video = document.createElement('video')
			  video.setAttribute('crossOrigin', 'anonymous') // 处理跨域，H5需后台支持，请求的视频资源响应投标需有Access-Control-Allow-Origin
			  video.setAttribute('src', this.absUrl(message.src))
			  video.setAttribute('width', width)
			  video.setAttribute('height', height)
			  video.setAttribute('preload', 'auto')
			  // uni.chooseVideo选择视频，当选用手机拍摄的视频时，地址是相对地址，如 _doc/uniapp_temp_1650594368317/camera/1650594390147.mp4
			  // 可播放，但是loadeddata一直不执行，会触发error事件，视频加载失败
			  // 应先转换成本地地址
			
			  return new Promise((resolve,reject)=>{
				  //上传文件
				   function dataURLtoFile(file,filename) {
				      const arr = file.split(',');
				      const mime = arr[0].match(/:(.*?);/)[1];
				      const bstr = atob(arr[1]);
					  console.log(bstr)
				      let n = bstr.length;
				      const u8arr = new Uint8Array(n);
				      while (n--) {
				        u8arr[n] = bstr.charCodeAt(n);
				      }
				  
				      return new File([u8arr], filename, {type: mime});
				   }
				  			
				  let blob = null
				  
				  video.addEventListener('loadeddata', function () {
						console.log('视频第一帧加载完')
						let canvas = document.createElement('canvas')
						let width = video.width // canvas的尺寸和图片一样
						let height = video.height
						canvas.width = width
						canvas.height = height
						canvas.getContext('2d').drawImage(video, 0, 0, width, height) // 绘制canvas
						dataURL = canvas.toDataURL('image/jpeg') // 转换为base64
					  
						console.log('getVideoPoster-dataURL', dataURL.slice(0, 16)) 
						blob = dataURLtoFile (dataURL,'video.png');
						let url = window.URL.createObjectURL(blob)
						resolve(url)
				  })
				  
				  video.addEventListener('error', err => {
						console.log('视频加载失败', err)
						reject(err)
				  })
			  })
			}
		}
	}
</script>

<style scoped>
	page {
		/* background-image: linear-gradient(45deg,#f4ffd5,#ffe5d5); */
		background-color: #fafafa;
	}
</style>
